<?php

namespace App\Http\Resources;

use Illuminate\Http\Resources\Json\Resource;

define("MY_PATH", 'http://app.git51.cn/storage/');

class ProgramResource extends Resource
{
    /**
     * Transform the resource into an array.
     *
     * @param  \Illuminate\Http\Request
     * @return array
     */
    public function toArray($request)
    {
        if ($this->program_file != null) {
            return  [
                'id' => $this->id,
                'name' => $this->name,
                'type' => optional($this->type)->name,
                'versionnumber' => $this->versionnumber,
                'program_file' => MY_PATH . $this->program_file,
                'download' => $this->download,
                'fize_size' => $this->getSize($this->program_file) . 'M',
                'versionCode' => $this->versionCode,
                'pkgName' => $this->apk,
                'logo' => 'http://app.git51.cn/uploads/' . $this->logo,
                'Introduction' => $this->description,
                'pic' => $this->getPic($this->imgs),
            ];
        }
        return  [
            'id' => $this->id,
            'name' => $this->name,
            'type' => optional($this->type)->name,
            'versionnumber' => $this->versionnumber,
            'program_file' => $this->program_file,
            'download' => $this->download,
            'versionCode' => $this->versionCode,
            'pkgName' => $this->apk,
            'logo' => 'http://app.git51.cn/uploads/' . $this->logo,
            'Introduction' => $this->description,
            'pic' => $this->getPic($this->imgs),
        ];
    }
    public function getSize($file)
    {
            $url = MY_PATH  . $file;
            $res = get_headers($url, true);
            $size = $res['Content-Length'] / 1024 / 1024;
            return sprintf('%.2f', $size);
    }
    public function getPic($imgs)
    {
        if ($imgs != null) {
            foreach ($imgs as $key => $val) {
                $imgs[$key] = 'http://app.git51.cn/uploads/' . $val;
            }
            return $imgs;
        }
    }
}
